import 'package:flutter/material.dart';
import 'dart:math' as math;

//卡片抖动动画封装
class CardShakeWidget extends StatefulWidget {
  const CardShakeWidget(
      {super.key, required this.child, this.startupAnimation = false});

  final Widget child;
  final bool startupAnimation;

  @override
  State<CardShakeWidget> createState() {
    return _CardShakeWidgetState();
  }
}

class _CardShakeWidgetState extends State<CardShakeWidget>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<double> _animation;

  double angle = 0;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
        vsync: this, duration: const Duration(milliseconds: 120));
    _animation =
        Tween(begin: math.pi / 120, end: math.pi * -0.005).animate(_controller)
          ..addListener(() {
            // print(_animation.value);
          });
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (widget.startupAnimation) {
      _controller.repeat(reverse: true);
    } else {
      _controller.stop();
    }

    return widget.startupAnimation
        ? AnimatedBuilder(
            animation: _animation,
            builder: (context, child) {
              return Transform.rotate(
                  angle: _animation.value, child: widget.child);
            },
          )
        : widget.child;
  }
}
